"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const defines_1 = require("../lib/defines");
const Rooms_1 = require("../lib/Rooms");
const client_1 = __importDefault(require("../kurento/client"));
function createClassroom(app) {
    const { socket, rooms: lRooms, intercom } = app.locals;
    const { userId } = socket.handshake.query;
    socket.on(defines_1.RequestMethod.create, async function create(data, cb) {
        const { room, mediaOptions, members } = data;
        const creator = socket.owner;
        const __room = lRooms[room.classId] || (lRooms[room.classId] = new Rooms_1.Room({
            ...room,
            socket,
            creator,
        }));
        socket.setInviteUser(members);
        lRooms[room.classId].setMediaOption(mediaOptions);
        __room.setMember(creator);
        const clientUtils = (0, client_1.default)((error) => { });
        app.locals.clientUtils = clientUtils;
        app.locals.client = await clientUtils.getClient((error, __client) => { });
        members.forEach((__member) => {
            const __socket = intercom[__member.userId];
            if (__socket && __member.userId !== userId) {
                const options = { room, creator, mediaOptions };
                socket
                    .to(__socket.id)
                    .timeout(60 * 1000)
                    .emit('invite', options, (error, [data]) => {
                    if (error) {
                        return;
                    }
                    socket
                        .emit('invited', {
                        member: __member,
                        status: data.status
                    });
                    socket
                        .broadcast
                        .in(room.classId)
                        .emit('invited', {
                        member: __member,
                        status: data.status
                    });
                });
            }
        });
        if (cb) {
            cb({ status: 'ok', resolve: 'created' });
        }
    });
}
exports.default = createClassroom;
